package com.badlogic.androidgames.mypirates.Sprite;

import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.mypirates.Constants;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;

public class Animation {
	Bitmap animatedCharacter;
	Point sheetSize;
	public Point currentFrame;
    public Point frameSize;
    int x;
    int y;
    int playCount = 0;
    
    public boolean IsActive;
    public boolean IsPlayed(){
    	return playCount == 1;
    }

    public int getFrameCount(){
    	return sheetSize.x * sheetSize.y;
    }
    
    int frameIndex;
    public int getFrameIndex(){
    	return sheetSize.x * currentFrame.y + currentFrame.x;
    }
    
    public void setFrameIndex(int value){
    	if (value >= sheetSize.x * sheetSize.y + 1)
        {
            try {
				throw new Exception(
				    "Specified frame index exeeds available frames");
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
    	
    	currentFrame.y = value / sheetSize.x;
    	currentFrame.x = value % sheetSize.x;
    }
    
    public Animation(Bitmap frameSheet, Point size, Point frameSheetSize, Point point) {
    	animatedCharacter = frameSheet;
    	frameSize = size;
    	sheetSize = frameSheetSize;
    	currentFrame = new Point();
    	//Offset
    	x = point.x;
    	y = point.y;
	}
    
    public void update(){
    	if(IsActive){
    		if(getFrameIndex() >= getFrameCount() - 1){
    			IsActive = false;
    			setFrameIndex(getFrameCount() - 1);
    		}
    		else{
    			currentFrame.x++;
    			if(currentFrame.x >= sheetSize.x){
    				currentFrame.x = 0;
    				currentFrame.y++;
    			}
    			if(currentFrame.y >= sheetSize.y){
    				currentFrame.y = 0;
    			}
    		}
    	}
    }
    
    public void draw(Graphics g){
    	Rect src = new Rect(frameSize.x * currentFrame.x, frameSize.y * currentFrame.y, frameSize.x * (currentFrame.x + 1), frameSize.y * (currentFrame.y + 1));
    	Rect dest = new Rect(Constants.InitialPositionX + Constants.MapPieceWidth * x,
    							Constants.InitialPositionY + Constants.MapPieceHeight * y,
    							Constants.InitialPositionX + Constants.MapPieceWidth * (x + 1),
    							Constants.InitialPositionY + Constants.MapPieceHeight * (y + 1));
    	g.drawBitmap(animatedCharacter, src, dest);
    }
    
    public void PlayFromFrameIndex(int frameIndex){
    	setFrameIndex(frameIndex);
    	IsActive = true;
    	playCount++;
    }
}
